let uiWaitTime = 1000;


function clickUI(uiObj, msg, waitTime) {
  try {
    if (!uiObj) {
      console.log(msg, '点击目标为空');
      return false;
    }
    if (uiObj.clickable && uiObj.clickable()) {
      uiObj.click();
    } else if (uiObj.bounds) {
      click(uiObj.bounds().centerX(), uiObj.bounds().centerY());
    } else {
      console.log(msg, '无法点击');
      return false;
    }
    console.log(msg || '点击');
    sleep(waitTime || uiWaitTime);
    return true;
  } catch (e) {
    console.trace(e);
    return false;
  }
}

function clickUIThrow(uiObj, msg, waitTime) {
  if (!clickUI(uiObj, msg, waitTime)) {
    throw new Error(msg + ', 找不到点击入口');
  }
}

function openTaskList() {
  let btn = className("android.widget.Button").text("赚喵币").findOne(uiWaitTime);
  clickUIThrow(btn, '打开任务列表');
  sleep(uiWaitTime);
}

function getBrowseButton() {
  while (true) {
    let packageName = currentPackage();
    if (packageName == 'com.eg.android.AlipayGphone') {
      return text("去浏览").findOne(uiWaitTime) || text("逛一逛").findOne(uiWaitTime);
    } else if (packageName == 'com.taobao.taobao') {
      return text("去浏览").findOne(uiWaitTime) || text("去完成").findOne(uiWaitTime) || text("去搜索").findOne(uiWaitTime);
    } else {
      toastLog('当前不是淘宝或支付宝界面，等待2秒:', packageName);
      sleep(2000);
    }
  }
}

function doTask() {
  openTaskList();
  let btn = getBrowseButton();
  while (btn) {
    clickUIThrow(btn, '开始浏览');
    while (!(desc('浏览15秒').findOne(uiWaitTime) && desc('得喵币').findOne(uiWaitTime))) {
      console.log('等待浏览开始...');
      sleep(uiWaitTime);
      break;
    }
    // 等待15秒
    console.log('等待浏览15秒...');
    sleep(20000);
    btn = desc('任务完成').findOne(5000);
    if (btn) {
      console.log('任务已完成');
    } else {
      console.log('任务未知是否完成，已等待5秒，结束浏览');
    }
    console.log('返回');
    back();
    sleep(uiWaitTime);
    btn = desc('继续退出').findOne(uiWaitTime);
    clickUI(ui, '继续退出');
    btn = getBrowseButton();
  }
  console.log('没有待浏览入口，退出自动浏览');
}

try {
  console.show();
  toastLog('自行打开猫猫页面, 10秒后开始');
  sleep(10000);
  doTask();  
  log(currentActivity())
} finally {
  console.hide();
}
